//
//  WeeklyLetterView.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/2/21.
//

import SwiftUI
import Kingfisher

//每周来信-详情
struct WeeklyLetterDetailView: View {
    
    var bean : WeeklyLetterBean
    var onCompletion: (() -> Void)? // 回调闭包
    @State private var visibleCharacters = 0
    @State private var timer: Timer?
    
    var body: some View {
        VStack(alignment: .leading,spacing : 0) {
            ZStack(alignment: .topTrailing) {
                VStack(alignment: .leading,spacing : 0) {
                    Text(bean.title ?? "致亲爱的你")
                        .font(.custom(IFontType.custom.rawValue, size: 30))
                        .foregroundStyle(.bgLetter)
                        .fontWeight(.bold)
                    Text(TimeUtils.getDate(time: bean.time, format: "yyyy年M月d日 HH:mm"))
                        .font(.system(size: 14))
                        .foregroundStyle(.bgLetter)
                        .padding(.top, 6)
                }.frame(maxWidth: .infinity,alignment: .leading)
                    .padding(.top,20)
                Image(.appIconClose3)
                    .resizable()
                    .frame(width: 23, height: 23, alignment: .topTrailing)
                    .onTapGesture {
                        self.onCompletion?()
                    }
            }.padding(.leading, 30)
                .padding(.trailing,15)
            //头像
            HStack(alignment: .bottom, spacing: 10) {
                KFImage(URL(string: bean.avatar.formatCdn()))
                    .resizable()
                    .placeholder {
                        Image(.appDefaultLogo)
                            .resizable()
                            .aspectRatio(contentMode: .fill)
                            .padding(15)
                            .background(.bgItemGray)
                    }
                    .aspectRatio(contentMode: .fill)
                    .frame(width: 50,height: 50)
                    .clipShape(Circle())
                Text(bean.name ?? "")
                    .font(.system(size: 14))
                    .foregroundStyle(.bgLetter)
                    .padding(.bottom, 8)
            }.padding(.leading, 30)
                .padding(.trailing,15)
                .padding(.top,12)
            //内容
            ZStack(alignment: .leading) {
                ScrollView {
                    Text(String(Array("　　\(bean.content ?? "")").prefix(visibleCharacters)))
                        .font(.system(size: 14))
                        .foregroundStyle(.bgLetter.opacity(0.8))
                        .lineSpacing(8)//行间距
                        .tracking(2)//字符
                        .fontWeight(.medium)
                        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
                }.scrollIndicators(.hidden)
            }.padding(.horizontal,30)
                .padding(.top, 20)
        }.frame(maxWidth: .infinity,maxHeight: .infinity,alignment: .topLeading)
            .navigationTitle("")
            .toolbar(.hidden, for: .navigationBar)
            .background {
                ZStack(alignment: .topTrailing) {
                    Image(.homeBgLetter)
                        .resizable() // 允许图片调整尺寸
                        .scaledToFill() // 充满容器（超出部分裁剪）
                    
                    Image(.homeIconBgLetter)
                        .resizable()
                        .aspectRatio(contentMode: .fit) // 保持原始宽高比，完全显示图片（不裁剪）
                        .frame(width: 35)
                        .padding(.trailing, 48)
                        .padding(.top, 100)
                }.edgesIgnoringSafeArea(.all) // 覆盖安全区域
                    .padding(0) // 消除图片自身内边距
                
            }.onAppear { startAnimation() }
            .onDisappear {
                timer?.invalidate()
                AudioPlayerManager.shared.pause()
            }
    }
    
    private func startAnimation() {
        if bean.read {
            visibleCharacters = bean.content?.count ?? 0
        } else {
            AudioPlayerManager.shared.playLocal(forResource:"typewriting",ofType:"mp3", looper : true)
            timer?.invalidate()
            visibleCharacters = 0
            let characters = Array(bean.content ?? "")
            timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { timer in
                if visibleCharacters < characters.count {
                    visibleCharacters += 1
                } else {
                    timer.invalidate()
                    AudioPlayerManager.shared.pause()
                }
            }
        }
    }
}

//#Preview {
//    WeeklyLetterDetailView()
//}

struct WeeklyLetterDetailView_Previews: PreviewProvider {
    static var previews: some View {

        configurePreviewEnvironment(for: WeeklyLetterDetailView(bean: getBean()))
           
    }
    
    static func getBean()-> WeeklyLetterBean {
        let bean = WeeklyLetterBean()
        bean.title = "致亲爱的你"
        bean.content = "致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你致亲爱的你"
        bean.name = "秦彻"
        return bean
    }
}

